<template>
    <div class="phase-begin-container">
        <!-- 搜索区域 -->
        <div class="search-section">
            <div class="search-left">
                <el-input v-model="searchForm.earNumber" placeholder="耳号..." style="width: 200px" clearable />
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="handleReset">重置</el-button>
            </div>
            <div class="search-right">
                <el-button type="primary" @click="handleAdd">+ 新增</el-button>
            </div>
        </div>

        <!-- 统计信息 -->
        <div class="stats-section">
            <el-alert :title="`已选择 ${selectedRows.length} 项`" type="info" :closable="false" show-icon />
        </div>

        <!-- 数据表格 -->
        <div class="table-section">
            <el-table :data="tableData" style="width: 100%" @selection-change="handleSelectionChange"
                v-loading="loading">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="PhaseBeginNumber" label="单据号" width="120" />
                <el-table-column prop="PhaseBeginDate" label="期初日期" width="120" />
                <el-table-column prop="EarNumber" label="耳号" width="100" />
                <el-table-column prop="HouseName" label="栋舍名称" width="120" />
                <el-table-column prop="FielName" label="栏位" width="120" />
                <el-table-column prop="SheepCount" label="羊只数量" width="100" />
                <el-table-column prop="Weight" label="重量(公斤)" width="100" />
                <el-table-column prop="Creator" label="创建人" width="100" />
                <el-table-column prop="CreateTime" label="创建时间" width="150" />
                <el-table-column prop="Modifier" label="修改人" width="100" />
                <el-table-column prop="ModifyTime" label="修改时间" width="150" />
                <el-table-column prop="Auditor" label="审核人" width="100" />
                <el-table-column prop="AuditTime" label="审核时间" width="150" />
            </el-table>
        </div>

        <!-- 分页 -->
        <div class="pagination-section">

            <el-pagination v-model:current-page="pagination.PageIndex" v-model:page-size="pagination.PageSize"
                :page-sizes="[10, 15, 20, 50, 100]" :total="pagination.TotalCount"
                layout="total, sizes, prev, pager, next, jumper" />
        </div>

        <!-- 新增/编辑对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px" @close="handleDialogClose">
            <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
                <el-form-item label="耳标号" prop="earTagNumber">
                    <el-input v-model="formData.earTagNumber" placeholder="请输入耳标号" />
                </el-form-item>
                <el-form-item label="期初日期" prop="initialDate">
                    <el-date-picker v-model="formData.initialDate" type="date" placeholder="请选择期初日期"
                        style="width: 100%" />
                </el-form-item>
                <el-form-item label="耳号" prop="earNumber">
                    <el-input v-model="formData.earNumber" placeholder="请输入耳号" />
                </el-form-item>
                <el-form-item label="体合名称" prop="breedName">
                    <el-input v-model="formData.breedName" placeholder="请输入体合名称" />
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select v-model="formData.gender" placeholder="请选择性别" style="width: 100%">
                        <el-option label="公" value="公" />
                        <el-option label="母" value="母" />
                    </el-select>
                </el-form-item>
                <el-form-item label="重量(公斤)" prop="weight">
                    <el-input-number v-model="formData.weight" :min="0" :precision="2" placeholder="请输入重量"
                        style="width: 100%" />
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleSubmit">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Sheep_BreedingRead, Sheep_BreedingWrite } from '@/utils/Interceptors'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const selectedRows = ref<PhaseBeginItem[]>([])
const formRef = ref()

// 搜索表单
const searchForm = reactive({
    earNumber: '',
    sheepType: '种母'
})

// 分页数据
const pagination = reactive({
    PageIndex: 1,
    PageSize: 20,
    TotalCount: 0
})

// 定义数据类型
interface PhaseBeginItem {
    id: number
    index: number
    earTagNumber: string
    initialDate: string
    earNumber: string
    breedName: string
    gender: string
    weight: string
    creator: string
    createTime: string
    modifier: string
    modifyTime: string
}

// 表格数据
const tableData = ref<any[]>([])

// 表单数据
const formData = reactive({
    id: null as number | null,
    earTagNumber: '',
    initialDate: '',
    earNumber: '',
    breedName: '',
    gender: '',
    weight: null as number | null
})

// 表单验证规则
const formRules = {
    earTagNumber: [
        { required: true, message: '请输入耳标号', trigger: 'blur' }
    ],
    initialDate: [
        { required: true, message: '请选择期初日期', trigger: 'change' }
    ],
    earNumber: [
        { required: true, message: '请输入耳号', trigger: 'blur' }
    ],
    breedName: [
        { required: true, message: '请输入体合名称', trigger: 'blur' }
    ],
    gender: [
        { required: true, message: '请选择性别', trigger: 'change' }
    ],
    weight: [
        { required: true, message: '请输入重量', trigger: 'blur' }
    ]
}


// 获取数据
const fetchData = async () => {
    loading.value = true
    try {
        Sheep_BreedingRead.get('/api/PhaseBegin/GetList', {
            params: {

                EarNumber: searchForm.earNumber,
                SheepType: searchForm.sheepType,
                PageIndex: pagination.PageIndex,
                PageSize: pagination.PageSize

            }
        }).then(res => {
            console.log(res);

            if (res.data.code === 200) {
                tableData.value = res.data.data.PageData
                pagination.TotalCount = res.data.data.TotalCount
            } else {
                tableData.value = []
                pagination.TotalCount = 0
            }
        })

    } catch (e) {
        ElMessage.error('获取数据失败')
    } finally {
        loading.value = false
    }
}

watch(pagination, () => {
    fetchData()
})
// 搜索
const handleSearch = () => {
    pagination.PageIndex = 1
    fetchData()
}

// 重置
const handleReset = () => {
    searchForm.earNumber = ''
    searchForm.sheepType = ''
    pagination.PageIndex = 1
    fetchData()
}

// 新增
const handleAdd = () => {
    router.push({ name: 'PhaseBeginAdd2' })
}

// 导入
const handleImport = () => {
    ElMessage.info('导入功能待开发')
}

// 查看
const handleView = (row: any) => {
    ElMessage.info(`查看 ${row.earTagNumber} 的详细信息`)
}

// 编辑
const handleEdit = (row: any) => {
    dialogTitle.value = '编辑期初信息'
    Object.assign(formData, row)
    dialogVisible.value = true
}

// 删除
const handleDelete = async (row: any) => {
    try {
        await ElMessageBox.confirm(
            `确定要删除耳标号为 ${row.earTagNumber} 的记录吗？`,
            '确认删除',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        // 这里应该调用删除API
        // await api.deletePhaseBegin(row.id)

        ElMessage.success('删除成功')
        fetchData()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 表格选择变化
const handleSelectionChange = (selection: PhaseBeginItem[]) => {
    selectedRows.value = selection
}



// 提交表单
const handleSubmit = async () => {
    if (!formRef.value) return

    try {
        await formRef.value.validate()

        // 这里应该调用保存API
        // if (formData.id) {
        //   await api.updatePhaseBegin(formData)
        // } else {
        //   await api.createPhaseBegin(formData)
        // }

        ElMessage.success(formData.id ? '更新成功' : '新增成功')
        dialogVisible.value = false
        fetchData()
    } catch (error) {
        console.error('表单验证失败:', error)
    }
}

// 关闭对话框
const handleDialogClose = () => {
    formRef.value?.resetFields()
    resetFormData()
}

// 重置表单数据
const resetFormData = () => {
    formData.id = null
    formData.earTagNumber = ''
    formData.initialDate = ''
    formData.earNumber = ''
    formData.breedName = ''
    formData.gender = ''
    formData.weight = null
}

// 组件挂载时获取数据
onMounted(() => {
    fetchData()
})
</script>

<style scoped>
.phase-begin-container {
    padding: 20px;
    background-color: #f5f5f5;
    min-height: 100vh;
}

.search-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-left {
    display: flex;
    align-items: center;
    gap: 10px;
}

.search-right {
    display: flex;
    align-items: center;
    gap: 10px;
}

.stats-section {
    margin-bottom: 20px;
}

.table-section {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    overflow: hidden;
}

.pagination-section {
    display: flex;
    justify-content: center;
    margin-top: 20px;
    padding: 20px;
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

/* 表格样式优化 */
:deep(.el-table) {
    border-radius: 8px;
}

:deep(.el-table th) {
    background-color: #f8f9fa;
    color: #495057;
    font-weight: 600;
}

:deep(.el-table td) {
    border-bottom: 1px solid #e9ecef;
}

:deep(.el-table tr:hover > td) {
    background-color: #f8f9fa;
}

/* 按钮样式优化 */
.el-button+.el-button {
    margin-left: 8px;
}

/* 分页样式优化 */
:deep(.el-pagination) {
    justify-content: center;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
    border-radius: 8px;
}

:deep(.el-dialog__header) {
    background-color: #f8f9fa;
    border-bottom: 1px solid #e9ecef;
    border-radius: 8px 8px 0 0;
}

:deep(.el-form-item__label) {
    font-weight: 600;
    color: #495057;
}

/* 响应式设计 */
@media (max-width: 768px) {
    .search-section {
        flex-direction: column;
        gap: 15px;
    }

    .search-left,
    .search-right {
        width: 100%;
        justify-content: center;
    }

    .phase-begin-container {
        padding: 10px;
    }
}
</style>